<template>
  <div class="back">
    <div class="login">
      <h3>叩丁狼商品管理系统</h3>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        class="demo-ruleForm"
      >
        <el-form-item prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入账号">
            <template #prefix>
              <el-icon :size="20" class="el-input__icon"><Avatar /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="ruleForm.password"
            type="password"
            autocomplete="off"
            placeholder="请输入密码"
          >
            <template #prefix>
              <el-icon :size="20" class="el-input__icon"><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance } from "element-plus";
import { Avatar, Lock } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { loginAPI } from "./api";
import { useRouter } from "vue-router";
const router = useRouter();
const ruleFormRef = ref<FormInstance>();

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    callback();
  }
};

const ruleForm = reactive({
  username: "",
  password: "",
});

const rules = reactive({
  username: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [{ validator: validatePass, trigger: "blur" }],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      loginAPI(ruleForm).then((res) => {
        if (res.code === 200) {
          localStorage.setItem("token", res.data.tokenHead + res.data.token);
          router.push('/index')

          ElMessage.success("登录成功!");
        }
      });
    } else {
      ElMessage.error("请输入账号或密码！");
      return false;
    }
  });
};
</script>

<style scoped lang="less">
.back {
  width: 100%;
  height: 100%;
  background-color: #2d3a4b;
  overflow: hidden;
  .login {
    width: 400px;
    margin: 200px auto 0;
    h3 {
      padding: 20px 0;
      color: #fff;
      text-align: center;
    }
    :deep(.el-input__wrapper) {
      background: #283443;
    }
    :deep(.el-input__inner) {
      height: 50px;
    }
    :deep(.el-button--primary) {
      width: 100%;
      height: 40px;
    }
  }
}
</style>